import permisionUtil from "./permission.js"
import { popup } from './native_popup.js'

const prefix = 'permision_'
const {
    uniPlatform,
    platform,
    osAndroidAPILevel
} = uni.getSystemInfoSync()

let modalContent = '';

function setModalContent(str = '') {
  modalContent = str;
}

function isManageAllFilesGranted() {
    try {
        const Environment = plus.android.importClass('android.os.Environment');
        const File = plus.android.importClass('java.io.File');
        const testFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
        const canRead = testFile.canRead();
        console.log('Environment.isExternalStorageManager()', Environment.isExternalStorageManager());
        console.log('testFile.canRead()', canRead);
        if (canRead) return true;
        return Environment.isExternalStorageManager();
    } catch (err) {
        console.error('checkManageAllFilesPermission failed:', err)
        return false
    }
}

async function chooseMedia({ type = 'image' }) {
    try {
        const cameraStatus = await permisionUtil.requestAndroidPermission('android.permission.CAMERA')
        "android.permission.READ_EXTERNAL_STORAGE"
        let mediaStatus;
        const comminStatus = await permisionUtil.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE');
        if (osAndroidAPILevel >= 33) {
            let mediaPermission;
            if (type ==='video') {
                mediaPermission = 'android.permission.READ_MEDIA_VIDEO';
            } else {
                mediaPermission = 'android.permission.READ_MEDIA_IMAGES';
            }
            mediaStatus = await permisionUtil.requestAndroidPermission(mediaPermission);
            if (!mediaStatus || !comminStatus) return -1;
        } else {
            mediaStatus = comminStatus;
        }

        const audioStatus = osAndroidAPILevel >= 33
            ? await permisionUtil.requestAndroidPermission('android.permission.READ_MEDIA_AUDIO')
            : 1;

            
        let hasManageAllFiles = true;
        if (osAndroidAPILevel >= 30) {
            hasManageAllFiles = isManageAllFilesGranted();
            if (!hasManageAllFiles) {
                setModalContent('我们需要您授予“文件和文档访问”权限，才能正常访问相册内容，请前往设置开启权限。');
            }
        }
        console.log('摄像头使用权：cameraStatus',cameraStatus)
        console.log('图库使用权：imageStatus',mediaStatus)

        console.log('音频使用权：audioStatus',audioStatus)

        console.log('文件文档使用权：hasManageAllFiles',hasManageAllFiles)

        if (cameraStatus === 1 && mediaStatus === 1 && audioStatus === 1 && hasManageAllFiles) {
            return 1;
        } else {
            return -1;
        }
    } catch (e) {
        console.error(`${type} 权限申请异常`, e);
        return 0;
    }
}

const permisionMap = {
    startBluetoothDevicesDiscovery: async function() {
        try {
            const status1 = await permisionUtil.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
            const status2 = await permisionUtil.requestAndroidPermission('android.permission.BLUETOOTH_SCAN')
            const status3 = await permisionUtil.requestAndroidPermission('android.permission.BLUETOOTH_CONNECT')
            if (status1 == 1 && status2 == 1 && status3 == 1) {
                return Promise.resolve(1)
            } else {
                return Promise.resolve(-1)
            }
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    scanCode: async function() {
        try {
            const status1 = await permisionUtil.requestAndroidPermission('android.permission.CAMERA')
            const status2 = osAndroidAPILevel >= 33 ? await permisionUtil.requestAndroidPermission('android.permission.READ_MEDIA_IMAGES') : await permisionUtil.requestAndroidPermission(
                'android.permission.READ_EXTERNAL_STORAGE')
            if (status1 == 1 || status2 == 1) {
                return Promise.resolve(1)
            } else {
                return Promise.resolve(-1)
            }
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    album: async function() {
        try {
            const status = osAndroidAPILevel >= 33 ? await permisionUtil.requestAndroidPermission('android.permission.READ_MEDIA_IMAGES') : await permisionUtil.requestAndroidPermission(
                'android.permission.READ_EXTERNAL_STORAGE')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    camera: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.CAMERA')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    chooseFile: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    chooseImage: () => chooseMedia({ type: 'image' }),
    chooseVideo: () => chooseMedia({ type: 'video' }),
    saveImageToPhotosAlbum: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    saveVideoToPhotosAlbum: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.WRITE_EXTERNAL_STORAGE')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    getLocation: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    chooseLocation: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    startLocationUpdate: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    makePhoneCall: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.CALL_PHONE')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    },
    getRecorderManager: async function() {
        try {
            const status = await permisionUtil.requestAndroidPermission('android.permission.RECORD_AUDIO')
            return Promise.resolve(status)
        } catch (e) {
            return Promise.resolve(0)
        }
    }
}

const resultHandler = function(args, err) {
    args.fail && args.fail(err)
    args.complete && args.complete(err)
}

let getRecorderManagerFlag = false
const _getRecorderManager = uni.getRecorderManager

const gotoAppPermissionSetting = function() {
    uni.showModal({
        title: '提示',
        content: modalContent || '您已关闭当前操作相关权限，请请手动前往设置。',
        confirmText: '立即设置',
        success: (res) => {
			  popup.close()
             if (res.confirm) {
               // #ifdef APP
               // 如果手自身系统、定位权限未开启，引导打开到系统设置页面
               if (plus.os.name === 'iOS') {
               	plus.runtime.openURL('app-settings://')
               } else {
               	var Intent = plus.android.importClass('android.content.Intent')
               	var Settings = plus.android.importClass('android.provider.Settings')
               	var Uri = plus.android.importClass('android.net.Uri')
               	var mainActivity = plus.android.runtimeMainActivity()
               	var intent = new Intent()
               	intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
               	var uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
               	intent.setData(uri)
               	mainActivity.startActivity(intent)
               }
               // #endif
               // #ifdef MP-WEIXIN
               uni.authorize({
                 scope: 'scope.userLocation',
                 success: (res) => console.log(res),
                 fail: (err) => console.log(err)
               });
               // #endif
               // #ifdef H5
               // H5会自动弹出权限请求
               navigator.geolocation.getCurrentPosition(
                 (res) => console.log(res),
                 (err) => console.log(err),
                 { maximumAge: 5000, timeout: 5000 }
               );
               // #endif
             }
        }
    })
}

/**
 * @func addPermisionInterceptor
 * @desc 添加权限申请说明拦截
 * @param {String} permisionName 要拦截的 uniApi 名称
 * @param {String} content 申请权限说明信息
 * @param {Boolean} once 只询问一次, 用户不同意申请或拒绝权限将无法使用 uniApi, 如果要继续使用 Api 先用 removePermisionInterceptor 函数移除拦截再调用 Api
 * @return 无
 * @Author huiliyi
 * @Email 1824159241@qq.com
 */
export const addPermisionInterceptor = function(permisionName, content, once) {
    if (uniPlatform != 'app' || platform != 'android') return
    const getRecorderManagerAdapter = function() {
        const recorder = _getRecorderManager()
        const _start = recorder.start.bind(recorder)
        recorder.start = async function(options) {
            const perm = uni.getStorageSync(prefix + permisionName)
            console.log('getRecorderManagerAdapter',once,perm);
            if (perm == 1) {
                _start(options)
                return
            }
            if (once && typeof perm == 'number') {
                console.error(`用户不同意申请或已拒绝权限`)
                return
            }
            try {
                // console.log("来了吗？!!!!")
                setTimeout(() => {
                  popup.show({ content }) // 避开渲染管线冲突:ml-citation{ref="6,8" data="citationList"}
                }, 300)
                let status = 0
                if (permisionMap[permisionName]) {
                    status = await permisionMap[permisionName]()
                } else {
                    status = 1
                    console.error(`addPermisionInterceptor fail, ${permisionName}-未配置获取权限方法`)
                }
                uni.setStorageSync(prefix + permisionName, status)
                if (status === 1) {
                    _start(options)
                }
                if (status === 0) {
                    console.error(`申请权限失败`)
                }
                if (status === -1) {
                    console.error(`用户已拒绝权限`)
                    gotoAppPermissionSetting()
                }
            } catch (err) {
                console.error(err)
            } finally {
                popup.close()
            }
        }
        return recorder
    }
    // console.log('执行addPermisionInterceptor----------------');
    if (permisionName == 'getRecorderManager') {
        if (getRecorderManagerFlag) return
        uni.getRecorderManager = getRecorderManagerAdapter
        getRecorderManagerFlag = true
        return
    }
    // console.log('执行uni.addInterceptor----------------');
    uni.addInterceptor(permisionName, {
        invoke(args) {
            if (args.sourceType && Array.isArray(args.sourceType) && args.sourceType.length == 1) permisionName = args.sourceType[0]
            return new Promise(async (resolve, reject) => {
                const perm = uni.getStorageSync(prefix + permisionName)
                if (perm == 1) {
                    resolve(args)
                    return
                }
                // console.log('uni.addIntercepto',once,perm);
                if (once && typeof perm == 'number') {
                    reject(args)
                    resultHandler(args, {
                        errMsg: '用户不同意申请或已拒绝权限'
                    })
                    return
                }
                try {
                    console.log("来了吗？???")
                    // 调用方法前 置空弹窗语句
                    setModalContent();
                    // 确保页面渲染完成后再显示
                    setTimeout(() => {
                        popup.show({ content }) // 避开渲染管线冲突:ml-citation{ref="6,8" data="citationList"}
                    }, 300)
                    // popup.show({ content })
                    let status = 0
                    if (permisionMap[permisionName]) {
                        status = await permisionMap[permisionName]()
                    } else {
                        status = 1
                        console.error(`addPermisionInterceptor fail, ${permisionName}-未配置获取权限方法`)
                    }
                    // console.log(status);
                    uni.setStorageSync(prefix + permisionName, status)
                    if (status === 1) {
                        resolve(args)
                    }
                    if (status === 0) {
                        reject(args)
                        resultHandler(args, {
                            errMsg: '申请权限失败'
                        })
                    }
                    if (status === -1) {
                        reject(args)
                        resultHandler(args, {
                            errMsg: '用户已拒绝该权限'
                        })
                        gotoAppPermissionSetting()
                        removePermisionInterceptor(permisionName);
                        addPermisionInterceptor(permisionName);
                    }
                } catch (err) {
                    reject(args)
                    resultHandler(args, err)
                } finally {
                    popup.close()
                }
            });
        },
        // success: (res) => {
        //     console.log(res);
        // },
        fail(err) {
            console.log('interceptor-fail', err)
            const errMsg = String(err?.errMsg)
            if (errMsg.includes('fail No Permission') || (errMsg.includes('fail') && errMsg.includes('权限'))) {
                uni.setStorageSync(prefix + permisionName, 0)
                gotoAppPermissionSetting()
            }
        },
        complete(res){
            console.log('complete',res);
        }
    })
}

/**
 * @func removePermisionInterceptor
 * @desc 移除权限申请说明拦截
 * @param {String} permisionName 要移除拦截的 uniApi 名称
 * @return 无
 * @Author huiliyi
 * @Email 1824159241@qq.com
 */
export const removePermisionInterceptor = function(permisionName) {
    if (permisionName == 'getRecorderManager') {
        getRecorderManagerFlag = false
        uni.getRecorderManager = _getRecorderManager
    }
    uni.removeInterceptor(permisionName)
    uni.removeStorageSync(prefix + permisionName)
}